package com.sba.core.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sba.core.domain.Menu;
import com.sba.core.repository.MenuRepository;
import com.sba.core.service.MenuService;

/**
 * 
 * @author feiliming
 *
 */
@Service
public class MenuServiceImpl implements MenuService {
	
	//private static final Logger log = LoggerFactory.getLogger(MenuServiceImpl.class);

	@Autowired
	MenuRepository menuRepository;

	@Override
	public Menu saveOrUpdate(Menu menu) {
		return menuRepository.save(menu);
	}
	
	@Override
	public Menu getById(Long id) {
		return menuRepository.findOne(id);
	}

	@Override
	public void delete(Long id) {
		menuRepository.delete(id);
	}

	@Override
	public List<Menu> getMenus() {
		return menuRepository.findAllByOrderBySortAsc();
	}

	@Override
	public List<Menu> getMenus(Long parentId, boolean isContainSub) {
		List<Menu> menus = menuRepository.findByIsShowAndParentIdOrderBySortAsc(1, parentId);
		if(isContainSub){
			getMenus(menus);
		}
		return menus;
	}
	
	/**
	 * 递归取子菜单
	 * @param menus
	 */
	private void getMenus(List<Menu> menus) {
		for(Menu m : menus){
			if(m.getIsLeaf() == 0){
				List<Menu> subMenus = menuRepository.findByIsShowAndParentIdOrderBySortAsc(1, m.getId());
				getMenus(subMenus);
				m.setSubMenus(subMenus);
			}
		}
	}

}
